<script setup lang="ts">
import { ref, onMounted, useTemplateRef } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Container from '@/components/Container/index.vue'
import TableComponent from '@/components/TableComponent/index.vue'
import AddArticleDialog from './components/AddArticleDialog.vue'
import UpdateArticleDialog from './components/UpdateArticleDialog.vue'
import { columns } from './data.ts'
import {
  queryArticleList,
  insertArticle,
  updateArticle,
  removeArticle,
  publishArticle,
} from '@/api/article'
import type {
  IArticleListResponse,
  IArticleAddRequest,
} from '@/api/interface/article'

defineOptions({
  name: 'Article',
})

// 获取文章列表数据
const articleList = ref<IArticleListResponse[]>([])
const loading = ref(false)
const getArticleList = async () => {
  try {
    loading.value = true
    const response = await queryArticleList()
    loading.value = false
    if (!Array.isArray(response)) return
    articleList.value = response
  } catch (error) {
    loading.value = false
    ElMessage.error(error as string)
  }
}
onMounted(getArticleList)

// 新增文章弹窗manager
const addArticleDialog =
  useTemplateRef<InstanceType<typeof AddArticleDialog>>('addArticleDialog')

// 打开新增文章弹窗，需要先将之前的数据清除
const openAddArticle = () => {
  if (!addArticleDialog.value) return
  addArticleDialog.value.reset()
  addArticleDialog.value.open()
}

// 处理新增文章弹窗提交事件
const addArticleSubmitHandler = async (data: IArticleAddRequest) => {
  // console.log('addArticleSubmitHandler', data)
  try {
    await insertArticle(data)
    ElMessage.success('新增成功! 记得发布哦')
    await getArticleList()
    addArticleDialog.value?.close()
  } catch (error) {
    ElMessage.error(error as string)
  }
}

// 编辑文章弹窗manager
const updateArticleDialog = useTemplateRef<
  InstanceType<typeof UpdateArticleDialog>
>('updateArticleDialog')

// 打开编辑文章弹窗，需要先将之前的数据清除
const openUpdateArticle = (row: IArticleAddRequest) => {
  if (!updateArticleDialog.value) return
  updateArticleDialog.value.reset()
  updateArticleDialog.value.open(row)
}

// 处理编辑文章弹窗提交事件
const updateArticleSubmitHandler = async (data: IArticleAddRequest) => {
  // console.log('updateArticleSubmitHandler', data)
  try {
    await updateArticle(data)
    ElMessage.success('编辑成功! ')
    await getArticleList()
    updateArticleDialog.value?.close()
  } catch (error) {
    ElMessage.error(error as string)
  }
}

// 删除文章处理
const deleteArticleHandler = async (id: number) => {
  if (!id) {
    return ElMessage.error('The id does not exist.')
  }
  const result = await ElMessageBox.confirm('确定删除该条文章吗？', '提示', {
    type: 'warning',
  })
  if (result === 'confirm') {
    await removeArticle(id)
    ElMessage.success(`文章${id}: 删除成功`)
    await getArticleList()
  }
}

// 发布文章处理
const publishArticleHandler = async (id: number) => {
  if (!id) {
    return ElMessage.error('The id does not exist.')
  }
  const result = await ElMessageBox.confirm('确定发布该条文章吗？', '提示', {
    type: 'info',
  })
  console.log(result)
  if (result === 'confirm') {
    await publishArticle(id)
    ElMessage.success(`文章${id}: 发布成功`)
    await getArticleList()
  }
}
</script>

<template>
  <Container
    class="article-manager"
    title="文章管理"
    search
    v-loading="loading"
    :columns="['add']"
    @on:add="openAddArticle"
  >
    <TableComponent
      index
      :is-pagination="false"
      :columns="columns"
      :initial="articleList"
    >
      <template #status="{ scope: { row } }">
        <ElTag type="primary" v-if="row.status === 'draft'">草稿</ElTag>
        <ElTag type="success" v-if="row.status === 'published'">已发布</ElTag>
        <ElTag type="danger" v-if="row.status === 'deleted'">已删除</ElTag>
      </template>
      <template #cover="{ scope: { row } }">
        <ElImage
          style="width: 50px; height: 50px; border-radius: 5px"
          fit="cover"
          :src="row.coverImage"
          alt="封面"
        >
        </ElImage>
      </template>
      <template #action="{ scope: { row } }">
        <ElButton type="primary" link @click="openUpdateArticle(row)">
          编辑
        </ElButton>
        <ElButton
          v-if="row.status !== 'published'"
          type="primary"
          link
          @click="publishArticleHandler(row.id)"
        >
          发布
        </ElButton>
        <ElButton type="danger" link @click="deleteArticleHandler(row.id)">
          删除
        </ElButton>
      </template>
    </TableComponent>
    <AddArticleDialog
      ref="addArticleDialog"
      @submit="addArticleSubmitHandler"
    />
    <UpdateArticleDialog
      ref="updateArticleDialog"
      @submit="updateArticleSubmitHandler"
    />
  </Container>
</template>

<style scoped lang="scss">
@use './index.scss';
</style>
